package com.lt.test.provider.service;

import com.lt.test.api.RedisService;
import com.lt.test.api.UserService;
import com.lt.test.common.constant.RedisConstant;
import com.lt.test.common.exception.CustomException;
import com.lt.test.entity.DO.RoleDO;
import com.lt.test.entity.DO.UserDO;
import com.lt.test.entity.DTO.CustomUser;
import com.lt.test.entity.DTO.MenuDTO;
import com.lt.test.entity.DTO.PageDTO;
import com.lt.test.entity.QueryModel.PageFilter;
import com.lt.test.entity.QueryModel.PageQueryModel;
import com.lt.test.entity.QueryModel.SysQueryModel;
import com.lt.test.provider.mapper.PrivilegeMapper;
import com.lt.test.provider.mapper.RoleMapper;
import com.lt.test.provider.mapper.UserMapper;
import com.lt.test.provider.mapper.UserOtherMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service("userService")
public class UserServiceImpl implements UserService {
	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	@Autowired
	private UserMapper userMapper;
	@Resource
	private UserOtherMapper userOtherMapper;
	@Resource
	private PrivilegeMapper privilegeMapper;
	@Resource
	private RedisService redisService;
	@Resource
	private RoleMapper roleMapper;

	@Override
	public List<MenuDTO> findUserMenusByRoleId(String roleId) throws CustomException {

		SysQueryModel queryModel = new SysQueryModel();
		queryModel.setRoleId(roleId);
		queryModel.setPrivilegeParentId("0");

		//获取顶层权限
		List<MenuDTO> menuDTOList = null;
		try {
			menuDTOList = privilegeMapper.findMenuByParentIdAndRoleId(queryModel);
			logger.debug("查询顶层权限成功 : " + menuDTOList);
		} catch (Exception e) {
			logger.error("查询顶层权限失败，查询参数 : " + queryModel);
			e.printStackTrace();
			throw new CustomException("查询顶层权限失败，查询参数 : " + queryModel);
		}

		//遍历顶层权限，获取二级权限
		for (MenuDTO menuDTO : menuDTOList) {
			//查询二级权限
			queryModel.setPrivilegeParentId(menuDTO.getId());
			List<MenuDTO> subMenuDTOTwoList = null;
			try {
				subMenuDTOTwoList = privilegeMapper.findMenuByParentIdAndRoleId(queryModel);
				logger.debug("查询二层权限成功 : " + subMenuDTOTwoList);
			} catch (Exception e) {
				logger.error("查询二层权限失败，查询参数 : " + queryModel);
				e.printStackTrace();
				throw new CustomException("查询二层权限失败，查询参数 : " + queryModel);
			}

			for (MenuDTO menuDTOTwo : subMenuDTOTwoList) {
				//查询三级权限
				queryModel.setPrivilegeParentId(menuDTOTwo.getId());
				List<MenuDTO> subMenuDTOThreeList = null;
				try {
					subMenuDTOThreeList = privilegeMapper.findMenuByParentIdAndRoleId(queryModel);
					logger.debug("查询三层权限成功 : " + subMenuDTOThreeList);
				} catch (Exception e) {
					logger.error("查询三层权限失败，查询参数 : " +queryModel);
					e.printStackTrace();
					throw new CustomException("查询三层权限失败，查询参数 : " +queryModel);
				}
			/*	for (MenuDTO menuDTOThree : subMenuDTOThreeList) {
					//查询四级权限
					queryModel.setPrivilegeParentId(menuDTOThree.getId());
					List<MenuDTO> subMenuDTOFourList = null;
					try {
						subMenuDTOFourList = privilegeMapper.findMenuByParentIdAndRoleId(queryModel);
						logger.debug("查询四层权限成功 : " + subMenuDTOFourList);
					} catch (Exception e) {
						logger.error("查询四层权限失败，查询参数 : " +queryModel);
						e.printStackTrace();
						throw new CustomException("查询四层权限失败，查询参数 : " +queryModel);
					}
					menuDTOThree.setSubMenus(subMenuDTOFourList);
				}*/
				//设置给二级菜单
				menuDTOTwo.setSubMenus(subMenuDTOThreeList);
			}
			menuDTO.setSubMenus(subMenuDTOTwoList);
		}
		logger.debug("用户菜单信息 : " + menuDTOList);
		return menuDTOList;
	}

	@Override
	public UserDO findUserByPhone(String phone)  throws CustomException {
		try {
			UserDO user =  userMapper.findUserByPhone(phone);
			logger.debug("根据用户phone获取到用户成功 : " + user);
			return user;
		} catch (Exception e) {
			logger.error("根据用户phone获取到用户失败，查询参数 ：" + phone);
			e.printStackTrace();
			throw new CustomException("根据用户phone获取到用户失败，查询参数 ：" + phone);
		}
	}


	@Override
	public CustomUser findCustomByPhone(String username)  throws CustomException{
		try {
			CustomUser user =  userMapper.findCustomByPhone(username);
			logger.debug("根据用户phone获取到用户成功 : " + user);
			return user;
		} catch (Exception e) {
			logger.error("根据用户phone获取到用户失败，查询参数 ：" + username);
			e.printStackTrace();
			throw new CustomException("根据用户phone获取到用户失败，查询参数 ：" + username);
		}
	}

	@Override
	public void registerUser(UserDO userDO) throws CustomException {
		userDO.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
		userDO.setRoleId("0");
		userDO.setDelete(false);
		userDO.setGmtCreate(new Date());
		userDO.setGmtModified(new Date());
		try {
			userMapper.insertUser(userDO);
			logger.debug("注册用户成功 : " + userDO);
		} catch (Exception e) {
			logger.error("注册用户失败 : " + userDO);
			e.printStackTrace();
			throw new CustomException("注册用户失败 : " + userDO);
		}
	}

	@Override
	public PageDTO<CustomUser> findUserByPage(Integer page, Integer pageSize, String sortedKey, String sortedValue, String filters) throws CustomException {
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		PageQueryModel pageQueryModel = new PageQueryModel();
		pageQueryModel.setBeginNum(beginNum);
		pageQueryModel.setEndNum(endNum);

		if("gmtCreateStr".equals(sortedKey)) {
			pageQueryModel.setSortName("UP.GMT_CREATE_STR");
		}else {
			pageQueryModel.setSortName("UP.GMT_MODIFIED_STR");
		}
		pageQueryModel.setSortOrder(("asc".equals(sortedValue) ? "asc" : "desc"));//防止sql注入

		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			List<PageFilter> filterList = new ArrayList<>();
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("username".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))){
					PageFilter filter = new PageFilter();
					filter.setFilterName("U.USERNAME");
					filter.setFilterType("LIKE");
					filter.setFilterValue("'%"+result.getString("data")+"%'");
					filterList.add(filter);
				}
				if("phone".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))){
					PageFilter filter = new PageFilter();
					filter.setFilterName("U.PHONE");
					filter.setFilterType("LIKE");
					filter.setFilterValue("'%"+result.getString("data")+"%'");
					filterList.add(filter);
				}
			}
			pageQueryModel.setFilters(filterList);
		}
		List<CustomUser> userList = null;
		int recordCount = 0;
		try {
			userList = userMapper.findUserByPage(pageQueryModel);
			recordCount = userMapper.getUserCount(pageQueryModel);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("获取用户列表失败");
		}
		PageDTO<CustomUser> result = new PageDTO<>(page, pageSize, userList, recordCount);
		return result;
	}

//	@Transactional(rollbackFor = Exception.class)
	@Override
	public void editUserInfo(CustomUser user, String oper) throws CustomException {
		user.setDelete(user.getState().equals("0") ? false : true);
		user.setGmtModified(new Date());
		user.setRoleId(user.getRoleName());
		switch (oper) {
			case "edit":
				if(user.getId() == null) {
					throw new CustomException("更新用户信息没有主键");
				}
				try {
					userMapper.editUserInfo(user);
					CustomUser customUser = userMapper.findCustomUserById(user.getId());
					if (customUser == null) {
						userOtherMapper.insertUserOther(user);
					}else {
						userOtherMapper.updateUserOther(user);
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new CustomException("更新用户信息失败");
				}
				break;
			case "add" :
				user.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
				user.setGmtCreate(new Date());
				try {
					userMapper.insertUser(user);
					userOtherMapper.insertUserOther(user);
				} catch (Exception e) {
					e.printStackTrace();
					throw new CustomException("添加用户失败");
				}
				break;
			default:
				throw new CustomException("不知道操作类型");
		}
	}

	@Override
	public void initializeUserPassword(UserDO user) throws CustomException {
		try {
			userMapper.initializeUserPassword(user);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("密码修改失败");
		}
	}

	@Override
	public List<String> findPermissionStrList(String roleId) throws CustomException {
		List<String> result = null;
		String redisRoleKey = RedisConstant.PLATFORM_PERMISSION_KRY_PRE+roleId;
		try {
			Object permission = redisService.get(redisRoleKey);
			if (permission == null) {
				result = privilegeMapper.findPermissionStrList(roleId);
				redisService.set(redisRoleKey, result,null);
				logger.info("设置了一个平台角色权限缓存，roleId="+roleId);
			}else {
				result = (List<String>) permission;
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("获取用户权限失败");
		}
	}

	@Override
	public Map<String, Object> findUSerRoleNameAndPrivilegeNames(String roleId) throws CustomException {
		Map<String, Object> result = new HashedMap();
		try {
			 RoleDO role = roleMapper.findRoleById(roleId);
			result.put("roleName", role.getRoleName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			List<String> privilegeNames =  privilegeMapper.findPermissionNamestrList(roleId);
			result.put("privilegeNames", privilegeNames);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return  result;

	}

	@Override
	public CustomUser findCustomUserById(String userId) throws CustomException {
		try {
			return userMapper.findCustomUserById(userId);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("获取用户失败");
		}
	}
}
